package com.hxht.cmp.utils;

import com.hxht.cmp.common.Constants;
import com.hxht.cmp.entity.Video;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * @author alice on 2017/10/11 0011.
 * @version 1.0
 * @since 1.0
 */
public class TimeLineThread implements Runnable {
    private final Logger logger = LoggerFactory.getLogger(TimeLineThread.class);

    private long time;
    private Video video;

    public TimeLineThread(long t, Video video) {
        time = t;
        this.video = video;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        Process p = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0"));//**TimeZone时区，加上这句话就解决啦**
        try {
            String path = Constants.TIMELINE_PATH + "/" + video.getUid() + "/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            logger.info(path);
            String start = simpleDateFormat.format(time * 1000);
            SimpleDateFormat sdfName = new SimpleDateFormat("HH_mm_ss");
            sdfName.setTimeZone(TimeZone.getTimeZone("GMT+0"));//**TimeZone时区，加上这句话就解决啦**
            String command = Constants.FFMPEG_DIR + "ffmpeg" + " -y -ss " + start + " -i " + video.getPlayUrl() + " -s 160*90 " + path + String.format("%08d", time) + ".png";
            logger.info("命令：" + command);
            p = Runtime.getRuntime().exec("su");
            DataOutputStream outputStream = new DataOutputStream(p.getOutputStream());
            outputStream.writeBytes(command + "\n");
            outputStream.flush();
            p.waitFor();
        } catch (Exception e) {
            logger.error(e.getMessage());
//            e.printStackTrace();
        } finally {
            try {
                if (null != p) {
                    p.getErrorStream().close();
                    p.getOutputStream().close();
                    p.getInputStream().close();
                    p.destroy();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
}
